<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="76px">
        <el-form-item label="输入类型">
          <el-select
            v-model="searchParam.type"
            placeholder="请选择输入类型"
            clearable
          >
            <el-option
              v-for="item in useDictionary('InputType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-tree-select
            v-model="searchParam.equipTypeId"
            node-key="id"
            :props="{
              children: 'nodes',
              label: 'assetTypeName',
              disabled: '',
            }"
            placeholder="请选择类型"
            check-strictly
            :data="deviceList"
            filterable
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="参数名称"
          prop="name"
          min-width="170"
          align="left"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="输入类型"
          prop="type"
          min-width="130"
          align="center"
          sortable
        >
          <template #default="scope">
            {{ useDictionary("InputType", scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column
          label="类型"
          prop="assetTypeName"
          min-width="180"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <!-- <el-table-column
          label="是否必须输入"
          prop="mustEnter"
          min-width="150"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.mustEnter === '1'"
              >是</el-tag
            >
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column
          label="内容类型"
          prop="inputType"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <span v-if="scope.row.type == 6 || scope.row.type == 7">{{
              scope.row.type == 6 ? "时间" : "日期"
            }}</span>
            <span v-else>
              {{ useDictionary("InputBoxType", scope.row.inputType) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="长度限制"
          prop="inputLength"
          min-width="110"
          show-overflow-tooltip
          align="right"
          sortable
        />
        <el-table-column
          label="小数点长度"
          prop="decimalPointLength"
          min-width="130"
          show-overflow-tooltip
          align="right"
          sortable
        />
        <el-table-column
          label="排序"
          prop="sort"
          min-width="100"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="是否启用"
          prop="enabled"
          min-width="120"
          align="center"
          sortable
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="180"
          align="left"
          show-overflow-tooltip
        />

        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
              >
                <i-ep-search />
              </el-button>
            </el-tooltip>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
            >
              <i-ep-edit />
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
            >
              <i-ep-delete />
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eamcustom-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :assetKind="assetKind"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { getAvailableListApi } from "@/utils/commonData";
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "CommonCustom",
  inheritAttrs: false,
});

const props = defineProps({
  assetKind: {
    type: Number,
    default: null,
  },
});

const { assetKind } = toRefs(props);

// 请求参数
const requestApi = "/eam/eamcustom/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  type: "",
  assetKind: assetKind.value,
  equipTypeId: "",
};

const deleteParam = {
  api: "/eam/eamcustom/delete",
  data: {
    assetKind: assetKind.value,
  },
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});
// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamcustom/get/${id}`,
    method: "get",
    data: {
      assetKind: assetKind.value,
    },
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开扩展参数表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改扩展参数";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增扩展参数";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开扩展参数表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "扩展参数详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eamcustom/deleteItem/${id}`,
      method: "post",
      data: {
        assetKind: assetKind.value,
      },
    });
    search();
  });
}

// 获取作业类型列表
const deviceList = ref(<any>[]);
async function getDeviceList() {
  const params = {
    assetKind: assetKind.value,
  };
  deviceList.value = (await getAvailableListApi(params)) ?? [];
}
getDeviceList();
</script>
